<!-- 党员活动台账 -->
<template>
  <div class="eduction_index">
    <!-- 按钮 -->
    <div class="top">
      <div class="left">
        <el-button
          type="success"
          size="small"
          @click="addUpload"
          style="background: #26a661"
          icon="el-icon-plus"
          >新增</el-button
        >
        <el-button
          type="success"
          size="small"
          @click="downInfo"
          icon="el-icon-bottom"
          :disabled="!urls.length"
          >下载</el-button
        >
        <el-button
          type="danger"
          size="small"
          @click="delInfo"
          icon="el-icon-delete"
          :disabled="!urls.length"
          >删除</el-button
        >
      </div>
      <!-- <div class="right">
        <div class="xuexi">
          <p>学习类型：</p>
          <el-select
            v-model="listParams.learningType"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in educationTypeArr"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </div>
        <div class="kejian">
          <p>标题：</p>
          <el-input
            v-model="listParams.title"
            placeholder="请输入……"
          ></el-input>
        </div>
        <el-button
          type="primary"
          size="small"
          @click="getEducationList"
          icon="el-icon-zoom-in"
          >搜索</el-button
        >
      </div> -->
    </div>

    <div style="padding: 10px" />

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="listArr"
      style="width: 100%"
      element-loading-text="Loading"
      border
      stripe
      fit
      highlight-current-row
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="50px" align="center" />

      <el-table-column label="序号" type="index" width="50px" align="center" />

      <el-table-column label="活动类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.activityType == 1">党员大会</span>
          <span v-if="scope.row.activityType == 2">支部委员会</span>
          <span v-if="scope.row.activityType == 3">党小组会</span>
          <span v-if="scope.row.activityType == 4">党课</span>
          <span v-if="scope.row.activityType == 5">党员统一活动日</span>
          <span v-if="scope.row.activityType == 6">特色活动</span>
        </template>
      </el-table-column>

      <el-table-column label="活动名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.activityTheme ? scope.row.activityTheme : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.activityStartTime ? scope.row.activityStartTime : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.activityEndTime ? scope.row.activityEndTime : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="活动地点" align="center">
        <template slot-scope="scope">
          {{ scope.row.activityPlace ? scope.row.activityPlace : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="参与人员" align="center">
        <template slot-scope="scope">
          <span
            v-for="(i, index) in JSON.parse(scope.row.participant)"
            :key="index"
          >
            {{ i.name }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="活动内容" align="center" width="400">
        <template slot-scope="scope">
          <div v-if="scope.row.activityContent">
            <div v-if="scope.row.activityContent.length > 50">
              <el-popover
                placement="top"
                :width="360"
                trigger="hover"
                :content="scope.row.activityContent"
              >
                <template #reference>
                  <p>{{ scope.row.activityContent.substring(0, 50) }}...</p>
                </template>
              </el-popover>
            </div>
            <div v-else>
              <p>{{ scope.row.activityContent }}</p>
            </div>
          </div>
          <p v-else>--</p>
        </template>
      </el-table-column>

      <el-table-column label="活动照片" align="center" width="400">
        <template slot-scope="scope">
          <span
            v-for="(i, index) in JSON.parse(scope.row.coverUrl)"
            :key="index"
          >
            <el-image
              style="width: 100px; height: 100px"
              :src="i"
              @click="seeImg(JSON.parse(scope.row.coverUrl))"
              :preview-src-list="srcList"
            >
            </el-image>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="附件" align="center">
        <template slot-scope="scope">
          <div
            v-for="(i, index) in JSON.parse(scope.row.accessoryUrl)"
            :key="index"
          >
            <span @click="prewFile(i)">{{ i.accessoryName }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="isShowAdd"
      width="50%"
      :show-close="false"
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="reset"
    >
      <el-form
        :model="dialogForm"
        ref="formRef"
        label-width="80px"
        :rules="formRules"
      >
        <el-form-item label="活动类型" prop="activityType">
          <el-select
            v-model="dialogForm.activityType"
            clearable
            filterable
            style="width: 100%"
            placeholder="请选择活动类型"
          >
            <el-option
              v-for="item in typeArr"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动名称" prop="activityTheme">
          <el-input
            v-model="dialogForm.activityTheme"
            placeholder="请填写活动名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属支部">
          <el-input v-model="dialogForm.djDeptName" disabled></el-input>
        </el-form-item>

        <el-form-item label="开始时间" prop="activityStartTime">
          <el-date-picker
            style="width: 100%"
            v-model="dialogForm.activityStartTime"
            type="datetime"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="activityEndTime">
          <el-date-picker
            style="width: 100%"
            v-model="dialogForm.activityEndTime"
            type="datetime"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动地点" prop="">
          <el-input
            v-model="dialogForm.activityPlace"
            placeholder="请选择活动地点"
          ></el-input>
        </el-form-item>
        <el-form-item label="参与人员" prop="">
          <el-select
            v-model="dialogForm.participant"
            clearable
            filterable
            multiple
            style="width: 100%"
            placeholder="请选择参与人员"
          >
            <el-option
              v-for="item in participantArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动内容" prop="activityContent">
          <el-input
            type="textarea"
            autosize
            v-model="dialogForm.activityContent"
            placeholder="请输入活动内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动照片" prop="">
          <el-upload
            :action="uploadUrl2"
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="removePic"
            :on-success="onSuccessPic"
            :headers="headers"
            :file-list="coverUrlPic"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="附件" prop="accessoryUrl">
          <el-upload
            :action="uploadUrl2"
            :headers="headers"
            :on-success="onSuccessFile"
            :on-remove="removeFile"
            :file-list="accessoryUrlFile"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button type="primary" @click="submitData('formRef')"
          >提 交</el-button
        >
      </div>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listParams.pageNum"
      :limit.sync="listParams.pageSize"
      @pagination="getEducationList"
    />
  </div>
</template>

<script>
import { uploadUrl2 } from "@/const";
import { getToken } from "@/utils/auth";
import { Base64 } from "js-base64";
import { serverUrl } from "@/look";
import { downLoadFileFn } from "@/utils/downFile";

import {
  apiUploadData, // 上传学习资料
  apiActivityLedgerList,
  apiTbUserInfoList, // 参与人员
  apiUploadTaiZhang, // 上传台账
  apiAllEnumMap, // 活动类型
  apidelMore, // 批量删除
  apiLoginUserInfo, // 获取登录人身份信息
} from "@/api2/ledger";

export default {
  components: {},
  data() {
    return {
      uploadUrl2,
      headers: {
        Authorization: getToken(),
        platform: 'WEB'
      },
      // -----------------
      coverUrlPic: [], // 保存上传的图片
      accessoryUrlFile: [], // 保存上传的附件

      typeArr: [], // 活动类型
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      participantArr: [], // 参与人员
      urls: [],
      fileSize: 200, //上传文件大小
      fileAccept: "",
      srcList: [],
      whetherVideosArr: [], // 多个视频链接
      isShowAdd: false,
      educationTypeArr: [],
      kejianTypeArr: [],
      formRules: {
        activityTheme: [
          {
            required: true,
            message: "请填写活动名称",
            trigger: "blur",
          },
        ],

        activityType: [
          {
            required: true,
            message: "请选择活动类型",
            trigger: "change",
          },
        ],
        activityStartTime: [
          {
            type: "date",
            required: true,
            message: "请选择开始时间",
            trigger: "change",
          },
        ],
        activityEndTime: [
          {
            type: "date",
            required: true,
            message: "请选择结束时间",
            trigger: "change",
          },
        ],

        accessoryUrl: [
          {
            required: true,
            message: "请选择文件",
            trigger: "change",
          },
        ],

        learningType: [
          { required: true, message: "请选择学习类型", trigger: "change" },
        ],

        url: [
          {
            required: true,
            message: "请输入链接地址",
            trigger: "blur",
          },
        ],
      },
      dialogForm: {
        seriesCoverUrl: [],
        fileUrl: [],
        coverUrl: [],
        accessoryUrl: [],
      },
      ruzhiApplyDialog: false,
      title: "",
      total: 0,
      listLoading: false,
      listArr: [],
      listParams: {
        pageNum: 1,
        pageSize: 10,
        djDeptId: JSON.parse(sessionStorage.getItem("loginUserinfo")).djDeptId,
      },
      participant: [],
    };
  },
  watch: {},
  created() {
    this.init();
  },
  methods: {
    // 将标准按时间转为时间戳
    getTimeStamp(chinaStandardTime) {
      return new Date(chinaStandardTime).getTime();
    },

    // 获取登录人信息
    getLoginUserInfo() {
      apiLoginUserInfo()
        .then((res) => {
          if (res.code == 0) {
            let loginUserinfo = JSON.parse(
              sessionStorage.getItem("loginUserinfo")
            );
            loginUserinfo.djDeptName = res.data.djDeptName;
            this.dialogForm.djDeptName = res.data.djDeptName;
            sessionStorage.setItem(
              "loginUserinfo",
              JSON.stringify(loginUserinfo)
            );
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取活动类型
    getAllEnumMap() {
      apiAllEnumMap()
        .then((res) => {
          if (res.code == 0) {
            this.typeArr = res.data;
          } else {
            this.typeArr = [];
          }
        })
        .catch((err) => {
          this.typeArr = [];
        });
    },

    // 图片上传
    onSuccessPic(response, file) {
      this.coverUrlPic.push({
        name: file.response.data.fileName,
        url: file.response.data.url,
        uid: file.uid,
      });
      this.dialogForm.coverUrl.push(file.response.data.url);
    },
    removePic(file) {
      let i = this.coverUrlPic.findIndex((v) => {
        return file.uid == v.uid;
      });
      this.coverUrlPic.splice(i, 1);
      this.dialogForm.coverUrl.splice(i, 1);
    },

    // 文件上传
    onSuccessFile(response, file) {
      this.accessoryUrlFile.push({
        name: file.response.data.fileName,
        url: file.response.data.url,
        uid: file.uid,
      });
      this.dialogForm.accessoryUrl.push({
        accessoryUrl: file.response.data.url,
        accessoryName: file.response.data.fileName,
      });
      this.$refs.formRef.clearValidate("accessoryUrl");
    },

    removeFile(file) {
      let i = this.accessoryUrlFile.findIndex((v) => {
        return file.uid == v.uid;
      });
      this.accessoryUrlFile.splice(i, 1);
      this.dialogForm.accessoryUrl.splice(i, 1);
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 获取参与人员列表
    getTbUserInfoList() {
      apiTbUserInfoList({ djDeptId: this.listParams.djDeptId })
        .then((res) => {
          if (res.code == 0) {
            this.participantArr = res.data;
          } else {
            this.participantArr = [];
          }
        })
        .catch((err) => {
          console.log(err);
          this.participantArr = [];
        });
    },

    selectionChange(val) {
      this.urls = val.map((v) => v.djBookId);
    },

    prewFile(file) {
      const extArr = [
        "swf",
        "avi",
        "flv",
        "mpg",
        "rm",
        "mov",
        "wav",
        "asf",
        "3gp",
        "mkv",
        "rmvb",
        "mp4",
        "jpg",
        "jpeg",
        "png",
        "gif",
      ];
      let name = file.accessoryName;
      const ext = name.substr(name.lastIndexOf(".") + 1); // 获取文件后缀名
      if (extArr.indexOf(ext) > -1) {
        window.open(file.accessoryUrl); // 在新标签页中打开文件
      } else {
        window.open(
          serverUrl +
            "onlinePreview?url=" +
            encodeURIComponent(Base64.encodeURI(file.accessoryUrl))
        );
      }
    },
    downloadFile(url) {
      var a = document.createElement("a");
      a.href = url;
      a.download = true;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    // 单个下载
    downInfo(row) {
      let url = [];
      if (this.urls.length) {
        url = this.listArr
          .filter((item) => this.urls.includes(item.djBookId))
          .map((item) => {
            return {
              accessoryUrl: JSON.parse(item.accessoryUrl)[0].accessoryUrl,
              accessoryName: JSON.parse(item.accessoryUrl)[0].accessoryName,
            };
          });
      }

      if (url.length) {
        for (let i = 0; i < url.length; i++) {
          downLoadFileFn(url[i].accessoryUrl, url[i].accessoryName);
        }
      }
    },

    // 删除
    delInfo() {
      let urls = this.urls.join(",");
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        apidelMore(urls)
          .then((res) => {
            if (res.code === 0) {
              this.msgSuccess("删除成功");
            } else {
              this.msgError("删除失败");
            }
            this.getEducationList();
          })
          .catch((err) => {
            console.log(err);
            this.msgError("删除失败");
            this.getEducationList();
          });
      });
    },

    // 编辑数据
    updateInfo(row) {
      this.isShowAdd = true;
      this.title = "编辑";
      this.dialogForm = row;
    },

    // 查看列表中的图片
    seeImg(imgSrc) {
      this.srcList = imgSrc;
    },

    // 添加链接
    addUrl() {
      let index = this.whetherVideosArr.length;
      this.whetherVideosArr.push({
        index,
        url: "",
      });
    },

    // 删除链接
    delUrl(index) {
      this.whetherVideosArr.splice(index, 1);
    },

    // 删除上传的图片
    onRemovePic(file, fileList) {
      this.dialogForm.seriesCoverUrl = [];
    },

    // 删除上传的文件
    onRemoveFile(file) {
      for (let i = 0; i < this.dialogForm.fileUrl.length; i++) {
        if (file.uid == this.dialogForm.fileUrl[i].uid) {
          this.dialogForm.fileUrl[i].splice(i, 1);
        }
      }
    },

    // 限制文件上传大小
    beforeAvatarUpload(file) {
      let size = 200;
      const isLtM = file.size / 1024 / 1024 < size;

      if (!isLtM) {
        this.$message.error(`上传文件大小不能超过${size} MB!`);
      }
      return isLtM;
    },

    // 封面上传成功
    handleSuccess(res) {
      this.dialogForm.seriesCoverUrl = [];
      if (res.code === 0) {
        this.dialogForm.seriesCoverUrl.push({
          name: res.data.fileName,
          url: res.data.url,
        });

        this.$nextTick(() => {
          this.$refs.formRef.validateField("seriesCoverUrl"); // 手动触发fileList校验规则
        });
        this.$forceUpdate();
      } else {
        this.msgError("上传失败");
        this.dialogForm.seriesCoverUrl = [];
      }
    },

    // 文件上传成功
    handleSuccessFile(res) {
      if (res.code === 0) {
        this.dialogForm.fileUrl.push({
          name: res.data.fileName,
          url: res.data.url,
        });
        this.$refs.formRef.validateField("fileUrl"); // 手动触发fileList校验规则
      } else {
        this.msgError("上传失败");
        this.dialogForm.fileUrl = [];
      }
    },

    // 提交
    submitData(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = {
            activityType: this.dialogForm.activityType, //活动类型
            activityTheme: this.dialogForm.activityTheme, // 活动名称
            djDeptName: this.dialogForm.djDeptName, // 所属支部
            activityStartTime: this.getTimeStamp(
              this.dialogForm.activityStartTime
            ), // 开始时间
            activityEndTime: this.getTimeStamp(this.dialogForm.activityEndTime), // 结束时间
            activityPlace: this.dialogForm.activityPlace, // 活动地点
            activityContent: this.dialogForm.activityContent, // 活动内容
            coverUrl: JSON.stringify(this.dialogForm.coverUrl), // 照片
            accessoryUrl: JSON.stringify(this.dialogForm.accessoryUrl), // 附件
            djDeptId: JSON.parse(sessionStorage.getItem("loginUserinfo"))
              .djDeptId,
            participant: [], // 参与人员
          };

          // 参与人员
          for (let i = 0; i < this.participantArr.length; i++) {
            for (let j = 0; j < this.dialogForm.participant.length; j++) {
              if (this.dialogForm.participant[j] == this.participantArr[i].id) {
                data.participant.push({
                  id: this.participantArr[i].id,
                  name: this.participantArr[i].name,
                });
              }
            }
          }
          data.participant = JSON.stringify(data.participant);

          this.isShowAdd = true;
          apiUploadTaiZhang(data)
            .then((res) => {
              if (res.code === 0) {
                this.msgSuccess("提交成功");
              } else {
                this.msgError("提交失败");
              }
              this.isShowAdd = false;
              this.getEducationList();
            })
            .catch((err) => {
              console.log(err);
              this.isShowAdd = false;
              this.msgError("提交失败");
              this.getEducationList();
            });
        }
      });
    },

    // 新增
    addUpload() {
      this.getLoginUserInfo();
      this.isShowAdd = true;
      this.title = "新增";
      this.getTbUserInfoList();
      this.getAllEnumMap();

      this.dialogForm.userName = JSON.parse(
        sessionStorage.getItem("loginUserinfo")
      ).name;

      this.dialogForm.userId = JSON.parse(
        sessionStorage.getItem("loginUserinfo")
      ).uid;
    },

    reset() {
      this.isShowAdd = false;
      this.dialogForm = {
        seriesCoverUrl: [],
        fileUrl: [],
        coverUrl: [],
        accessoryUrl: [],
      };
      this.coverUrlPic = [];
      this.accessoryUrlFile = [];
      this.$nextTick(() => {
        this.$refs["formRef"].clearValidate();
      });
    },
    // 获取数据列表
    getEducationList() {
      this.listLoading = true;
      apiActivityLedgerList(this.listParams)
        .then((res) => {
          if (res.code === 0) {
            this.listArr = res.data;
            this.total = res.total;
          } else {
            this.total = 0;
            this.listArr = [];
          }
          this.listLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.total = 0;
          this.listArr = [];
          this.listLoading = false;
        });
    },

    // 项目初始化
    init() {
      this.getEducationList();
    },
  },
};
</script>

<style lang="scss" scoped>
.eduction_index {
  padding: 15px;
  .top {
    height: 35px;
    display: flex;
    justify-content: space-between;
    .right {
      display: flex;
      .xuexi,
      .kejian {
        margin: 0 20px;
        display: flex;
        p {
          width: 30%;
        }
      }
    }
  }
  .upload_url {
    display: flex;
    align-items: center;
    margin: 4px 0;
    .el-icon-circle-plus-outline,
    .el-icon-remove-outline {
      cursor: pointer;
      margin-left: 10px;
      font-size: 20px;
    }
    .el-icon-circle-plus-outline:hover {
      color: #409eff;
    }
    .el-icon-remove-outline:hover {
      color: #f56c6c;
    }
  }
}
</style>
